const moment = require("moment");
const math = require("mathjs");

math.config({
    number: "BigNumber", // Default type of number:
    // 'number' (default), 'BigNumber', or 'Fraction'
    precision: 20 // Number of significant digits for BigNumbers
});

module.exports = {
    async createApp(app) {
        if (app.template_id === 1) {
            await doodoo
                .model("shop")
                .forge({
                    app_id: app.id,
                    name: app.name, // 店铺名称
                    status: 1
                })
                .save();
        }
    },
    async productAnalysis(wxaId, userId, productId) {
        const refDate = moment().format("YYYYMMDD");
        const analysis = await doodoo
            .model("analysis_product_user_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("user_id", userId);
                qb.where("product_id", productId);
                qb.where("ref_date", refDate);
            })
            .fetch();

        const product = await doodoo
            .model("analysis_product_user_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("product_id", productId);
                qb.where("ref_date", refDate);
            })
            .fetch();

        const productAnalysis = await doodoo
            .model("analysis_product_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("ref_date", refDate);
            })
            .fetch();
        const productEffect = await doodoo
            .model("analysis_product_effect_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("product_id", productId);
                qb.where("ref_date", refDate);
            })
            .fetch();

        if (!analysis) {
            await doodoo
                .model("analysis_product_user_summary")
                .forge({
                    wxa_id: wxaId,
                    product_id: productId,
                    user_id: userId,
                    ref_date: refDate
                })
                .save();
        }
        if (productAnalysis) {
            if (!analysis) {
                productAnalysis.visitor = math.format(
                    math.eval(`1 + ${productAnalysis.visitor}`)
                );
            }
            if (!product) {
                productAnalysis.visit = math.format(
                    math.eval(`1 + ${productAnalysis.visit}`)
                );
            }
            await doodoo
                .model("analysis_product_summary")
                .forge({
                    id: productAnalysis.id,
                    view: math.format(math.eval(`1 + ${productAnalysis.view}`)),
                    visitor: productAnalysis.visitor,
                    visit: productAnalysis.visit
                })
                .save();
        } else {
            await doodoo
                .model("analysis_product_summary")
                .forge({
                    wxa_id: wxaId,
                    view: 1,
                    visitor: 1,
                    visit: 1,
                    ref_date: refDate
                })
                .save();
        }

        if (productEffect) {
            if (!analysis) {
                productEffect.visitor = math.format(
                    math.eval(`1 + ${productEffect.visitor}`)
                );
            }
            await doodoo
                .model("analysis_product_effect_summary")
                .forge({
                    id: productEffect.id,
                    view: math.format(math.eval(`1 + ${productEffect.view}`)),
                    visitor: productEffect.visitor
                })
                .save();
        } else {
            await doodoo
                .model("analysis_product_effect_summary")
                .forge({
                    wxa_id: wxaId,
                    product_id: productId,
                    view: 1,
                    visitor: 1,
                    trade: 0,
                    ref_date: refDate
                })
                .save();
        }
    },
    async productAnalysisTrade(orderId) {
        const refDate = moment().format("YYYYMMDD");
        const order = await doodoo
            .model("order")
            .query(qb => {
                qb.where("id", orderId);
                qb.where("pay_status", 1);
            })
            .fetch({ withRelated: ["detail"] });
        if (!order) {
            return;
        }
        if (!order.detail.length) {
            return;
        }
        const shop = await doodoo
            .model("shop")
            .query(qb => {
                qb.where("id", order.shop_id);
            })
            .fetch();
        if (!shop) {
            return;
        }
        if (!shop.app_id) {
            return;
        }
        const wxa = await doodoo
            .model("wxa")
            .query(qb => {
                qb.where("app_id", shop.app_id);
            })
            .fetch();
        if (!wxa) {
            return;
        }
        const trade = await doodoo
            .model("analysis_wxa_daily_summary")
            .query(qb => {
                qb.where("ref_date", refDate);
                qb.where("wxa_id", wxa.id);
            })
            .fetch();
        if (trade) {
            await doodoo
                .model("analysis_wxa_daily_summary")
                .forge({
                    id: trade.id,
                    trade: math.format(math.eval(`1 + ${trade.trade}`))
                })
                .save();
        } else {
            await doodoo
                .model("analysis_wxa_daily_summary")
                .forge({ wxa_id: wxa.id, ref_date: refDate, trade: 1 })
                .save();
        }

        const detail = order.detail;
        for (const i in detail) {
            const productEffect = await doodoo
                .model("analysis_product_effect_summary")
                .query(qb => {
                    qb.where("wxa_id", wxa.id);
                    qb.where("product_id", detail[i].product_id);
                    qb.where("ref_date", refDate);
                })
                .fetch();

            if (productEffect) {
                await doodoo
                    .model("analysis_product_effect_summary")
                    .forge({
                        id: productEffect.id,
                        trade: math.format(
                            math.eval(`1 + ${productEffect.trade}`)
                        )
                    })
                    .save();
            } else {
                await doodoo
                    .model("analysis_product_effect_summary")
                    .forge({
                        wxa_id: wxa.id,
                        product_id: detail[i].product_id,
                        view: 1,
                        visitor: 1,
                        trade: 1,
                        ref_date: refDate
                    })
                    .save();
            }
        }
    },
    async payTrue(trade) {
        const order = await doodoo
            .model("order")
            .query(qb => {
                qb.where("orderid", trade.tradeid);
            })
            .fetch();
        if (order) {
            await doodoo
                .model("order")
                .forge({
                    id: order.id,
                    pay_status: 1
                })
                .save();
        }
    },
    //1 表示分销，普通商品，预售 0表示团购
    async addSale(from = 1, trade) {
        if (Number(from) === 1 && Number(trade.type === 0)) {
            const order = await doodoo
                .model("order")
                .query(qb => {
                    qb.where("orderid", trade.tradeid);
                })
                .fetch({ withRelated: ["detail.product"] });

            const detail = order.detail;
            const product = [];
            const sku = [];
            if (detail.length) {
                for (const i in detail) {
                    if (detail[i].product.id) {
                        const productSale =
                            Number(detail[i].product.sale) +
                            Number(detail[i].num);

                        const productObj = {
                            id: detail[i].product.id,
                            sale: productSale
                        };
                        product.push(productObj);
                    }
                    if (detail[i].sku_id) {
                        const productsku = await doodoo
                            .model("productsku")
                            .query(qb => {
                                qb.where("id", detail[i].sku_id);
                            })
                            .fetch();
                        if (productsku.id) {
                            const skuSale =
                                Number(productsku.sale) + Number(detail[i].num);
                            const skuStore =
                                Number(productsku.store) -
                                Number(detail[i].num);
                            const skuObj = {
                                id: productsku.id,
                                sale: skuSale,
                                store: skuStore > 0 ? skuStore : 0
                            };
                            sku.push(skuObj);
                        }
                    }
                }
                if (product.length) {
                    await doodoo.bookshelf.Collection.extend({
                        model: doodoo.model("product")
                    })
                        .forge(product)
                        .invokeThen("save");
                }
                if (sku.length) {
                    await doodoo.bookshelf.Collection.extend({
                        model: doodoo.model("productsku")
                    })
                        .forge(sku)
                        .invokeThen("save");
                }
            }
        }

        if (Number(from) === 0) {
            console.log("111");
            const order_info = await doodoo
                .model("pintuan_order")
                .query(qb => {
                    qb.where("orderid", "=", trade.tradeid);
                })
                .fetch();

            // 增加sku
            if (order_info.sku_id > 0) {
                doodoo.hook.run("addProductSale", order_info.sku_id, 1);
            }

            // 增加商品表销量
            const product = await doodoo
                .model("product")
                .query(qb => {
                    qb.where("id", "=", order_info.product_id);
                })
                .fetch();
            const new_num = Number(product.sale) + 1;

            await doodoo
                .model("product")
                .forge({
                    id: order_info.product_id,
                    sale: new_num
                })
                .save();
        }
    }
};
